package com.yuneec.fly.activities;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yuneec.android.media.widget.VideoView;
import com.yuneec.droneservice.ServiceManager;
import com.yuneec.droneservice.model.ControllerLocation;
import com.yuneec.droneservice.model.ControllerVersion;
import com.yuneec.droneservice.model.JoystickValues;
import com.yuneec.droneservice.protocol.analysis.Analysis;
import com.yuneec.droneservice.protocol.analysis.MediaStreamReceiver;
import com.yuneec.droneservice.utils.ByteUtils;
import com.yuneec.fly.GlobalParams;
import com.yuneec.fly.R;
import com.yuneec.fly.dialogs.ProgressDialog;
import com.yuneec.fly.events.EventBusFactory;
import com.yuneec.fly.events.feedbackEvent.SwitchChangedEvent;
import com.yuneec.fly.events.uiEvent.CameraConnectChangedEvent;
import com.yuneec.fly.events.uiEvent.ChangeMapToolsVisibleEvent;
import com.yuneec.fly.events.uiEvent.ClickViewEvent;
import com.yuneec.fly.events.uiEvent.ConnectionChangeEvent;
import com.yuneec.fly.events.uiEvent.ExitCheckEvent;
import com.yuneec.fly.events.uiEvent.ExitEvent;
import com.yuneec.fly.events.uiEvent.FragmentEvent;
import com.yuneec.fly.events.uiEvent.MissionStatusChangeEvent;
import com.yuneec.fly.events.uiEvent.ProgressEvent;
import com.yuneec.fly.events.uiEvent.SetDroneLocationEvent;
import com.yuneec.fly.events.uiEvent.SetPanAndTiltAngle;
import com.yuneec.fly.events.uiEvent.SwitchMapActionEvent;
import com.yuneec.fly.events.uiEvent.UpdateRecordTimeEvent;
import com.yuneec.fly.fragments.BasicInfoFragment;
import com.yuneec.fly.fragments.CameraControllerFragment;
import com.yuneec.fly.fragments.MapFragment;
import com.yuneec.fly.fragments.MessageFragment;
import com.yuneec.fly.presenters.CameraPresenter;
import com.yuneec.fly.presenters.Cgo3ProPresenter;
import com.yuneec.fly.presenters.Cgo4Presenter;
import com.yuneec.fly.presenters.ConstantPresenter;
import com.yuneec.fly.presenters.MainActivityPresenter;
import com.yuneec.fly.utils.SharePrefUtil;
import com.yuneec.fly.utils.inject.annotation.ContentView;
import com.yuneec.fly.utils.inject.annotation.ViewInject;
import com.yuneec.fly.views.CounterView;
import com.yuneec.fly.views.DroneCompass;
import com.yuneec.fly.views.FocusView;
import com.yuneec.fly.views.ViewWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    private static final boolean showMap = true;//是否显示地图，不显示地图的时候视频最大化
    private VideoView mVideoView;
    private RelativeLayout videoFrame;
    private View hideLayout;
    private View mainGuideLayout;
    private View waypointsGuideLayout;
    private View fenceGuideLayout;
    private DroneCompass compassView;
    private CounterView recordTimeView;
    private FocusView focusView;
    private View videoEmptyView;

    @ViewInject(R.id.channelTestTV)
    private TextView channelTestTV;

    @ViewInject(R.id.versionTV)
    private TextView versionTV;

    @ViewInject(R.id.gpsTestTV)
    private TextView gpsTestTV;

    @ViewInject(R.id.controllerGPSTV)
    private TextView controllerGPSTV;

    @ViewInject(R.id.joystickTestTV)
    private TextView joystickTestTV;

    private int miniVideoHeight;
    private int miniVideoWidth;
    private int maxVideoHeight;
    private int maxVideoWidth;

    private BasicInfoFragment basicInfoFragment;
    private MapFragment mapFragment;
    private CameraControllerFragment cameraControllerFragment;
    private View detailView;
    private MessageFragment messageFragment;
    private Handler handler = new Handler();

    private MainActivityPresenter mainActivityPresenter;
    private CameraPresenter cameraPresenter;
//

    private long pts = 0;
    //    private int mCacheSize = 0;
//    private byte[] bcache = new byte[1024 * 64];
    private long droneFeedbackCount = 0;
    private long controllerFeedbackCount = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        droneFeedbackCount = 0;
        controllerFeedbackCount = 0;
        hideLayout = findViewById(R.id.hideLayout);
        mainGuideLayout = findViewById(R.id.mainGuideLayout);
        waypointsGuideLayout = findViewById(R.id.waypointsGuideLayout);
        fenceGuideLayout = findViewById(R.id.fenceGuideLayout);
        compassView = (DroneCompass) findViewById(R.id.compassView);
        recordTimeView = (CounterView) findViewById(R.id.recordTimeView);
        recordTimeView.setDuration(3600);// 1 hour max
        recordTimeView.setStyle(CounterView.COUNT_UP);
        focusView = (FocusView) findViewById(R.id.focusView);
        videoEmptyView = findViewById(R.id.videoEmptyView);
        videoEmptyView.bringToFront();
        mainActivityPresenter = new MainActivityPresenter();
        progressDialog = new ProgressDialog();
        miniVideoHeight = getResources().getDimensionPixelOffset(R.dimen.mini_video_height);
        miniVideoWidth = getResources().getDimensionPixelOffset(R.dimen.mini_video_width);
        maxVideoHeight = getResources().getDimensionPixelOffset(R.dimen.max_video_height);
        maxVideoWidth = getResources().getDimensionPixelOffset(R.dimen.max_video_width);

        basicInfoFragment = (BasicInfoFragment) getFragmentManager().findFragmentById(R.id.basicInfoFragment);
        basicInfoFragment.getView().bringToFront();
        mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
        cameraControllerFragment = (CameraControllerFragment) getFragmentManager().findFragmentById(R.id.cameraControllerFragment);
        messageFragment = (MessageFragment) getFragmentManager().findFragmentById(R.id.messageFragment);
        messageFragment.getView().bringToFront();
//        videoView = (IjkVideoView) findViewById(R.id.video_view);
        videoFrame = (RelativeLayout) findViewById(R.id.videoFrame);

        detailView = findViewById(R.id.detail);
        setListener();
//        LogUtils.allowD=false;
//        LogUtils.allowI=false;
//        LogUtils.allowW=false;
//        LogUtils.allowV=false;
        videoFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("zzd", "send aoa data(hello) to id 554");
                ServiceManager.getInstance().writeAOAData(554, media);
//                initVideo();
            }
        }, 10000);
    }

    private final byte[] media = "hello".getBytes();
    private Toast toast;

    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (toast == null) {
                    toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT);
                } else {
                    toast.setText(msg);
                }
                toast.show();
            }
        });
    }

    private void initVideo() {
        getCameraType();
        Log.e("zzd", "init video! prev:" + preType + "  now:" + GlobalParams.cameraType);
        if (preType == GlobalParams.cameraType) {
            return;
        }
        if (mVideoView == null) {
            Log.d("zzd", "init mVideoView");
            try {
                mVideoView = (VideoView) findViewById(R.id.videoView);
                mVideoView.setVideoPath("rtsp://192.168.42.1:554/live");
                mVideoView.requestFocus();
                mVideoView.start();
                Log.d("zzd", "init mVideoView ok!!!");
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("zzd", "init mVideoView failed!");
            }
        }
        Log.d("zzd", "send aoa data(hello) to id 554");
        ServiceManager.getInstance().writeAOAData(554, media);
        ServiceManager.getInstance().setMediaStreamReceiver(new MediaStreamReceiver() {

            private final int MAX_NALU_LEN = 1024 * 1024;
            private byte[] naluBuffer = new byte[MAX_NALU_LEN];

            private int getNalu(Analysis.Message msg) {
//           int pTimestamp =  ByteUtils.byteArrayToInt(msg.body(), msg.offset(), false);
                int naluLength = ByteUtils.byteArrayToInt(msg.body(), msg.offset() + 4, false);
                int naluOffset = ByteUtils.byteArrayToInt(msg.body(), msg.offset() + 8, false);
                System.arraycopy(msg.body(), msg.offset() + 12, naluBuffer, naluOffset, msg.length() - 12);
                if ((naluOffset + msg.length() - 12) == naluLength) {
                    return naluLength;
                } else {
                    return -1;
                }
            }


            @Override
            public void handleMessage(Analysis.Message msg) {
                Log.d("stream", "stream data:" + msg.length());
//                if (isNaluHead(msg.body())) {
//                    if (mCacheSize != 0) {
//                        mVideoView.pushH264Stream(bcache, mCacheSize, pts);
//                    }
//                    System.arraycopy(msg.body(), 0, bcache, 0, msg.length());
//                    mCacheSize = msg.length();
//                } else {
//                    System.arraycopy(msg.body(), 0, bcache, mCacheSize, msg.length());
//                    mCacheSize += msg.length();
//
//                }
//
                int naluLen = getNalu(msg);
                if (naluLen > 0) {
                    mVideoView.pushH264Stream(naluBuffer, naluLen, pts);
                }


                pts += 3003;
            }
        });

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                videoEmptyView.setVisibility(View.INVISIBLE);
            }
        }, 2200);
        preType = GlobalParams.cameraType;
    }

    @Override
    public void finish() {
        releasePreCamera(true);
        super.finish();
    }

    private void releasePreCamera() {
        releasePreCamera(false);
    }

    private void releasePreCamera(boolean exitApp) {
        if (!exitApp) {
            videoEmptyView.setVisibility(View.VISIBLE);
            videoEmptyView.bringToFront();
        }
        ServiceManager.getInstance().setMediaStreamReceiver(null);
        if (cameraPresenter != null) {
            cameraPresenter.stop();
            cameraPresenter = null;
        }
    }

    private void bringTestInfoToFront() {
        channelTestTV.bringToFront();
        gpsTestTV.bringToFront();
        versionTV.bringToFront();
        controllerGPSTV.bringToFront();
        joystickTestTV.bringToFront();
    }

    private void setListener() {
        if (showMap) {
            videoFrame.setOnClickListener(new View.OnClickListener() {
                boolean animating = false;
                ViewWrapper wrapper = new ViewWrapper(videoFrame);
                ObjectAnimator objectAnimator;

                @Override
                public void onClick(View v) {
                    if (animating) {
                        return;
                    }
                    if (GlobalParams.videoViewStatus == GlobalParams.ViewStatus.MINI) {
                        animating = true;
                        showMapTools();
                        if (objectAnimator == null) {
                            PropertyValuesHolder setWidth = PropertyValuesHolder.ofInt("width", miniVideoWidth, maxVideoWidth);
                            PropertyValuesHolder setHeight = PropertyValuesHolder.ofInt("height", miniVideoHeight, maxVideoHeight);
                            objectAnimator = ObjectAnimator.ofPropertyValuesHolder(wrapper, setWidth, setHeight).setDuration(300);
                            objectAnimator.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mapFragment.mapViewContainer.getLayoutParams();
                                    layoutParams.width = miniVideoWidth;
                                    layoutParams.height = miniVideoHeight;
                                    mapFragment.mapViewContainer.setLayoutParams(layoutParams);
                                    mapFragment.mapViewContainer.requestLayout();
                                    GlobalParams.mapViewStatus = GlobalParams.ViewStatus.MINI;
                                    messageFragment.getView().bringToFront();
                                    channelTestTV.bringToFront();
                                    gpsTestTV.bringToFront();
                                    if (GlobalParams.CameraType.CGO4 == GlobalParams.cameraType) {
                                        focusView.setVisibility(View.VISIBLE);
                                        focusView.bringToFront();
                                    }
                                    mapFragment.getView().bringToFront();
                                    GlobalParams.videoViewStatus = GlobalParams.ViewStatus.MAX;
                                    animating = false;
                                    showHideButton();
                                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) recordTimeView.getLayoutParams();
                                    params.topMargin += 50;
                                    recordTimeView.setLayoutParams(params);
                                    messageFragment.getView().bringToFront();
                                    bringTestInfoToFront();
                                    cameraControllerFragment.changeVisable(true);
                                }
                            });
                        }
                        hideMapTools();
                        videoFrame.bringToFront();
                        videoEmptyView.bringToFront();
                        basicInfoFragment.getView().bringToFront();
                        showHideButton();
                        objectAnimator.start();
                    }
                }
            });
            findViewById(R.id.hideMiniViewBtn).setOnClickListener(new View.OnClickListener() {
                boolean animating = false;
                ViewWrapper wrapper1 = new ViewWrapper(hideLayout);
                ViewWrapper wrapper2 = new ViewWrapper(mapFragment.mapViewContainer);
                ViewWrapper wrapper3 = new ViewWrapper(videoFrame);
                ObjectAnimator objectAnimator1;
                ObjectAnimator objectAnimator2;

                @Override
                public void onClick(View v) {
                    if (animating) {
                        return;
                    }
                    PropertyValuesHolder setWidth = PropertyValuesHolder.ofInt("width", miniVideoWidth, 0);
                    PropertyValuesHolder setHeight = PropertyValuesHolder.ofInt("height", miniVideoHeight, 0);
                    showMapTools();
                    if (GlobalParams.videoViewStatus == GlobalParams.ViewStatus.MINI) {
                        animating = true;
                        compassView.setVisibility(View.VISIBLE);
                        if (objectAnimator1 == null) {
                            objectAnimator1 = ObjectAnimator.ofPropertyValuesHolder(wrapper1, setWidth, setHeight).setDuration(200);
                            objectAnimator1.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    compassView.bringToFront();
                                    messageFragment.getView().bringToFront();
                                    bringTestInfoToFront();
                                    GlobalParams.videoViewStatus = GlobalParams.ViewStatus.MIN;
                                    animating = false;
                                }
                            });

                        }
                        ObjectAnimator.ofPropertyValuesHolder(wrapper3, setWidth, setHeight).setDuration(200).start();
                        objectAnimator1.start();
                    } else if (GlobalParams.mapViewStatus == GlobalParams.ViewStatus.MINI) {
                        animating = true;
                        compassView.setVisibility(View.VISIBLE);
                        if (objectAnimator2 == null) {
                            objectAnimator2 = ObjectAnimator.ofPropertyValuesHolder(wrapper1, setWidth, setHeight).setDuration(200);
                            objectAnimator2.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    compassView.bringToFront();
                                    messageFragment.getView().bringToFront();
                                    bringTestInfoToFront();
                                    GlobalParams.mapViewStatus = GlobalParams.ViewStatus.MIN;
                                    animating = false;
                                }
                            });
                        }
                        ObjectAnimator.ofPropertyValuesHolder(wrapper2, setWidth, setHeight).setDuration(200).start();
                        objectAnimator2.start();
                    }
                }
            });
            compassView.setOnClickListener(new View.OnClickListener() {
                boolean animating = false;
                ViewWrapper wrapper1 = new ViewWrapper(hideLayout);
                ViewWrapper wrapper2 = new ViewWrapper(mapFragment.mapViewContainer);
                ViewWrapper wrapper3 = new ViewWrapper(videoFrame);
                ObjectAnimator objectAnimator1;
                ObjectAnimator objectAnimator2;

                @Override
                public void onClick(View v) {
                    if (animating) {
                        return;
                    }
                    PropertyValuesHolder setWidth = PropertyValuesHolder.ofInt("width", 0, miniVideoWidth);
                    PropertyValuesHolder setHeight = PropertyValuesHolder.ofInt("height", 0, miniVideoHeight);
                    showMapTools();
                    if (GlobalParams.videoViewStatus == GlobalParams.ViewStatus.MIN) {
                        animating = true;
                        compassView.setVisibility(View.GONE);
                        if (objectAnimator1 == null) {
                            objectAnimator1 = ObjectAnimator.ofPropertyValuesHolder(wrapper1, setWidth, setHeight).setDuration(200);
                            objectAnimator1.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    messageFragment.getView().bringToFront();
                                    bringTestInfoToFront();
                                    GlobalParams.videoViewStatus = GlobalParams.ViewStatus.MINI;
                                    animating = false;
                                }
                            });
                        }
                        ObjectAnimator.ofPropertyValuesHolder(wrapper3, setWidth, setHeight).setDuration(200).start();
                        objectAnimator1.start();
                    } else if (GlobalParams.mapViewStatus == GlobalParams.ViewStatus.MIN) {
                        animating = true;
                        compassView.setVisibility(View.GONE);
                        showMapTools();
                        if (objectAnimator2 == null) {
                            objectAnimator2 = ObjectAnimator.ofPropertyValuesHolder(wrapper1, setWidth, setHeight).setDuration(200);
                            objectAnimator2.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    messageFragment.getView().bringToFront();
                                    bringTestInfoToFront();
                                    GlobalParams.mapViewStatus = GlobalParams.ViewStatus.MINI;
                                    animating = false;
                                }
                            });
                        }
                        ObjectAnimator.ofPropertyValuesHolder(wrapper2, setWidth, setHeight).setDuration(200).start();
                        objectAnimator2.start();
                    }
                }
            });
            mapFragment.mapViewContainer.setOnClickListener(new View.OnClickListener() {
                boolean animating = false;
                ViewWrapper wrapper = new ViewWrapper(mapFragment.mapViewContainer);
                ObjectAnimator objectAnimator;

                @Override
                public void onClick(View v) {
                    if (animating) {
                        return;
                    }
                    if (GlobalParams.videoViewStatus == GlobalParams.ViewStatus.MAX) {
                        if (objectAnimator == null) {
                            PropertyValuesHolder setWidth = PropertyValuesHolder.ofInt("width", miniVideoWidth, maxVideoWidth);
                            PropertyValuesHolder setHeight = PropertyValuesHolder.ofInt("height", miniVideoHeight, maxVideoHeight);
                            objectAnimator = ObjectAnimator.ofPropertyValuesHolder(wrapper, setWidth, setHeight).setDuration(200);
                            objectAnimator.addListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    detailView.bringToFront();
                                    messageFragment.getView().bringToFront();
                                    channelTestTV.bringToFront();
                                    gpsTestTV.bringToFront();
                                    showMapTools();
                                    showHideButton();
                                    GlobalParams.videoViewStatus = GlobalParams.ViewStatus.MINI;
                                    GlobalParams.mapViewStatus = GlobalParams.ViewStatus.MAX;
                                    animating = false;
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) videoFrame.getLayoutParams();
                                            layoutParams.width = miniVideoWidth;
                                            layoutParams.height = miniVideoHeight;
                                            videoFrame.setLayoutParams(layoutParams);
                                            videoFrame.requestLayout();
                                            videoFrame.bringToFront();
                                            videoEmptyView.bringToFront();
                                            showHideButton();
                                            messageFragment.getView().bringToFront();
                                            bringTestInfoToFront();
                                            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) recordTimeView.getLayoutParams();
                                            params.topMargin -= 50;
                                            recordTimeView.setLayoutParams(params);
                                        }
                                    });
                                }
                            });
                        }
                        animating = true;
                        if (GlobalParams.CameraType.CGO4 == GlobalParams.cameraType) {
                            focusView.setVisibility(View.GONE);
                        }
                        basicInfoFragment.getView().bringToFront();
                        cameraControllerFragment.changeVisable(false);
                        objectAnimator.start();
                    }
                }
            });
            findViewById(R.id.closeWaypointGuideView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharePrefUtil.saveInt(MainActivity.this, SharePrefUtil.KEY.KEY_WAYPOINTS_GUIDE_SHOWED, 1);
                    waypointsGuideLayout.setVisibility(View.GONE);
                }
            });
            findViewById(R.id.closeFenceGuideView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharePrefUtil.saveInt(MainActivity.this, SharePrefUtil.KEY.KEY_FENCE_GUIDE_SHOWED, 1);
                    fenceGuideLayout.setVisibility(View.GONE);
                }
            });
            findViewById(R.id.closeMainGuideView).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SharePrefUtil.saveInt(MainActivity.this, SharePrefUtil.KEY.KEY_MAIN_GUIDE_SHOWED, 1);
                    mainGuideLayout.setVisibility(View.GONE);
                }
            });
            focusView.setOnFocusListener(new FocusView.OnFocusListener() {
                @Override
                public void onFocus(FocusView.PressEventType pressEventType, float xRatio, float yRatio) {
                    if (isFastDoubleClick()) {
                        return;
                    }
//                    if (cameraPresenter != null && cameraPresenter instanceof Cgo4Presenter) {
//                        ((Cgo4Presenter) cameraPresenter).fixFocus(pressEventType, xRatio, yRatio);
//                    }
                }
            });
        } else {
            findViewById(R.id.hideMiniViewBtn).setVisibility(View.GONE);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) videoFrame.getLayoutParams();
            layoutParams.width = maxVideoWidth;
            layoutParams.height = maxVideoWidth;
            videoFrame.setLayoutParams(layoutParams);
            videoFrame.bringToFront();
            mapFragment.getView().setVisibility(View.GONE);
            basicInfoFragment.getView().bringToFront();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onClickMapViewContainer(final ClickViewEvent event) {
        switch (event.view) {
            case mapviewContainer:
                mapFragment.mapViewContainer.performClick();
                break;
            case compassView:
                compassView.performClick();
                break;
        }
    }

    private static long lastClickTime = 0L;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 600) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public void hideMapTools() {
        EventBusFactory.getUiBus().post(new ChangeMapToolsVisibleEvent(false));
    }

    public void showMapTools() {
        EventBusFactory.getUiBus().post(new ChangeMapToolsVisibleEvent(true));
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
//        videoView.release(true);
        super.onDestroy();
    }

    public void showHideButton() {
        hideLayout.bringToFront();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSwitchMapAction(SwitchMapActionEvent event) {
        FragmentTransaction t = getFragmentManager().beginTransaction();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMissionStatusChange(final MissionStatusChangeEvent event) {
        FragmentTransaction t = getFragmentManager().beginTransaction();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetPanAndTiltAngle(SetPanAndTiltAngle event) {
        compassView.setCameraAngle(event.panAngle);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetDroneLocation(SetDroneLocationEvent event) {
        compassView.setDroneAngle(event.routeAngle);
    }

    private ProgressDialog progressDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProgress(ProgressEvent event) {
        if (progressDialog == null) {
            return;
        }
        if (event.show) {
            if (!progressDialog.isAdded() || !progressDialog.isVisible()) {
                progressDialog.setMessage(event.msg == null ? "" : event.msg);
                progressDialog.show(getFragmentManager(), event.msg);
            }
        } else {
            if (getFragmentManager() != null && progressDialog.isAdded() || progressDialog.isVisible() || !progressDialog.isHidden()) {
                progressDialog.dismiss();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExitCheck(ExitCheckEvent event) {
        mainActivityPresenter.exitCheck();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSwitchChanged(SwitchChangedEvent event) {
        if (cameraPresenter != null) {
            switch (event.switchChanged.hwId) {
                case GlobalParams.CAMERA_KEY_INDEX:
                    if (event.switchChanged.newState == 0) {
                        cameraPresenter.takePhoto();
                    }
                    break;
                case GlobalParams.VIDEO_KEY_INDEX:
                    if (event.switchChanged.newState == 0) {
                        cameraPresenter.record();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onBackPressed() {
        mainActivityPresenter.exitCheck();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExit(ExitEvent event) {
        ControllerLocation location = ConstantPresenter.getInstance().getControllerLocation();
        if (location != null) {
            if (location.latitude != 0) {
                SharePrefUtil.saveFloat(this, SharePrefUtil.KEY.KEY_LAST_CONTROLLER_LATITUDE, (float) location.latitude);
                SharePrefUtil.saveFloat(this, SharePrefUtil.KEY.KEY_LAST_CONTROLLER_LONGITUDE, (float) location.longitude);
            }
        }
        finish();
    }

    private Runnable exitRunnable = new Runnable() {

        @Override
        public void run() {
            finish();
        }
    };

    private GlobalParams.CameraType preType;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCameraConnectChangedEvent(CameraConnectChangedEvent event) {
        GlobalParams.CameraType cameraType = GlobalParams.cameraType;
        getCameraType();
        if (GlobalParams.cameraType != null && cameraType != GlobalParams.cameraType) {
            releasePreCamera();
            compassView.setCameraShowable(true);
            switch (GlobalParams.cameraType) {
                case CGO3P:
                    cameraPresenter = Cgo3ProPresenter.getInstance();
                    break;
                case CGO4:
                    cameraPresenter = Cgo4Presenter.getInstance();
                    break;
                default:
                    cameraPresenter = Cgo3ProPresenter.getInstance();
                    break;
            }
            cameraControllerFragment.setCameraPresenter(cameraPresenter);
            initVideo();
        } else if (GlobalParams.cameraType == null) {
            preType = null;
            compassView.setCameraShowable(false);
            releasePreCamera();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleFragmentEvent(FragmentEvent event) {
        if (event.getmEvent() == FragmentEvent.EVENT_ADD_SHOW_REMOVE_UPDATE_FRAGMENT) {
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            Fragment fragment = getFragmentManager().findFragmentByTag(event.getmFragmentName());
            if (fragment == null) {
                return;
            }
            if (!fragment.isVisible()) {
                fragmentTransaction.setCustomAnimations(R.animator.fragment_slide_right_in, R.animator.fragment_slide_right_out).add(R.id.detail, fragment, event.getmFragmentName()).commit();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (GlobalParams.updating) {
            GlobalParams.updating = false;
            Toast.makeText(this, "Update success", Toast.LENGTH_SHORT).show();
        }
        String action = intent.getAction();
        Log.d("st10c", "onNewIntent  action:" + action);
//        if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
//            ServiceManager.getInstance().reInit(this);
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateRecordTimeView(UpdateRecordTimeEvent event) {
        if (event.isRecording) {
            recordTimeView.start(event.recordTime);
            recordTimeView.setVisibility(View.VISIBLE);
            recordTimeView.bringToFront();
        } else {
            recordTimeView.stop();
            recordTimeView.setVisibility(View.INVISIBLE);
        }
    }

    private void int2String(StringBuilder sb, int[] vs) {
        for (int v : vs) {
            sb.append(v).append("  ");
        }
    }


    private final Runnable updateUI = new Runnable() {
        @Override
        public void run() {
            //GetVersionEvent
            ControllerVersion version = ConstantPresenter.getInstance().getControllerVersion();
            StringBuffer versionStr = new StringBuffer("");
            if (version != null) {
                versionStr.append("FirmwareVersion:").append(version.getFirmwareVersion());
                versionStr.append("\nHardwareVersion:").append(version.getHardwareVersion());
                versionStr.append("\nMcuVersion:").append(version.getMcuVersion());
            }
            versionTV.setText(versionStr);
            //DroneFeedbackEvent
            if (GlobalParams.droneFeedback != null) {
                droneFeedbackCount++;
                String s = "=====Drone====="
                        + "\nCount: " + droneFeedbackCount
                        + "\r\nLat: " + GlobalParams.droneFeedback.latitude
                        + "\r\nLon: " + GlobalParams.droneFeedback.longitude
                        + "\r\nAlt: " + GlobalParams.droneFeedback.altitude
                        + "\r\nSates: " + GlobalParams.droneFeedback.satellitesNum
                        + "\r\nhSpeed: " + GlobalParams.droneFeedback.hSpeed
                        + "\r\nyaw: " + GlobalParams.droneFeedback.yaw
                        + "\r\npitch: " + GlobalParams.droneFeedback.pitch;
                gpsTestTV.setText(s);
                if (basicInfoFragment.isVisible()) {
                    basicInfoFragment.updateDroneFeedback();
                }
            }
            //ControllerLocationEvent
            ControllerLocation location = ConstantPresenter.getInstance().getControllerLocation();
            StringBuffer locationStr = new StringBuffer();
            if (location != null) {
                locationStr.append("=====Controller=====");
                controllerFeedbackCount++;
                locationStr.append("\nCount:").append(controllerFeedbackCount);
                locationStr.append("\nLat:").append(location.latitude);
                locationStr.append("\nLon:").append(location.longitude);
                locationStr.append("\nAlt:").append(location.altitude);
                locationStr.append("\nSates:").append(location.satelliteCount);
                locationStr.append("\nSpeed:").append(location.speed);
                locationStr.append("\nAngle:").append(location.angle);
                locationStr.append("\nAccuracy:").append(location.accuracy);
                if (basicInfoFragment.isVisible()) {
                    basicInfoFragment.updateControllerLocation();
                }
            }
            controllerGPSTV.setText(locationStr);
            //JoystickValues
            JoystickValues joystickValues = ConstantPresenter.getInstance().getJoystickValues();
            StringBuilder joystickStr = new StringBuilder();
            if (joystickValues != null) {
                joystickStr.append("j:");
                int2String(joystickStr, joystickValues.getjVaules());

                joystickStr.append("k:");
                int2String(joystickStr, joystickValues.getkVaules());

                joystickStr.append("s:");
                int2String(joystickStr, joystickValues.getsVaules());

                joystickStr.append("b:");
                int2String(joystickStr, joystickValues.getbVaules());
            }
            joystickTestTV.setText(joystickStr);

            //ChannelValuesEvent
            int[] channels = ConstantPresenter.getInstance().getChannels();
            StringBuffer channelsStr = new StringBuffer();
            for (int i = 0; channels != null && i < channels.length; i++) {
                channelsStr.append("Channel ").append(i + 1).append(" : ").append(channels[i]).append('\n');
            }
            channelsStr.append("RightWheel:" + ConstantPresenter.getInstance().getRightWHeel());
            channelTestTV.setText(channelsStr);

            handler.postDelayed(this, 100);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectionChangeEvent(ConnectionChangeEvent event) {
        if (event.isConnected) {
            handler.postDelayed(updateUI, 100);
        } else {
            handler.removeCallbacks(updateUI);
            versionTV.setText("");
            gpsTestTV.setText("");
            joystickTestTV.setText("");
            channelTestTV.setText("");
        }
        Toast.makeText(this, event.isConnected ? "AOA connected!" : "AOA disConnected!", Toast.LENGTH_SHORT).show();
    }

    private synchronized void getCameraType() {
        if (GlobalParams.connectedCamera == null) {
            return;
        }
        String currentSSID = GlobalParams.connectedCamera;
        if (currentSSID == null) {
            GlobalParams.cameraType = null;
        }
        if (currentSSID.contains("CGO3P"))
            GlobalParams.cameraType = GlobalParams.CameraType.CGO3P;
        if (currentSSID.contains("CGO3") && !currentSSID.contains("CGO3P"))
            GlobalParams.cameraType = GlobalParams.CameraType.CGO3;
        if (currentSSID.contains("CGO4") || currentSSID.contains("YUNEEC"))
            GlobalParams.cameraType = GlobalParams.CameraType.CGO4;
        if (currentSSID.contains("CGOT") || currentSSID.contains("CGOET"))
            GlobalParams.cameraType = GlobalParams.CameraType.CGOET;
        if (currentSSID.contains("cgopro"))
            GlobalParams.cameraType = GlobalParams.CameraType.CGOPRO;
        if (currentSSID.contains("fire") || currentSSID.contains("hdracer")) {
            GlobalParams.cameraType = GlobalParams.CameraType.FIREBIRD;
        } else {
            GlobalParams.cameraType = GlobalParams.CameraType.CGO3P;
        }
    }

    private boolean isNaluHead(byte[] bytes) {
        if (bytes[0] == 0x00 && bytes[1] == 0x00 && bytes[2] == 0x00 && bytes[3] == 0x01)
            return true;
        else
            return false;
    }

    private static int need2print = 5;
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[need2print * 2];


        for (int j = 0; j < need2print; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
}
